// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var router = require("../hash/pageRouter");
	var dialog = require("dialog");
	var validate = require("validate");
	var databind = require("databind");
	var css_detail_info = require("./applyMain2.css");
	//var html_valuation = require("./applyValuation.html");
	var tools = require("tools");
	var constant = require("constant");
	var html_createSuppliers = require("./html_createSuppliers.html");
	var str1 = '<div class="fuid" ><a class="financeEvidentiary" fileUuid="" target="_blank"><img class="short" src="../../../res/png/contract1.png" /></a><img style="cursor:pointer;" class="sub1" src="../../../res/png/sub_icon.png" /><span></span></div>';
	var flag = false;
	var productType = 5;
	var success = false;
	var enterpriseId;
	var materialFileuuid = []; //证明材料FileUuid
	var templateName = []; //模版名称
	var templateId = []; //模版ID
	var commodityCategoryId = [];
	var evidentiaryCategoryId = [];
	var evidentiaryId = []
	var oData
	var financeId;
	var html;
	var fileElementId;
	var bulkstockObj = {
		bulkstockId: [],
		bulkstockName: [],
		specificationName: [],
		bulkstockNumber: [],
		measurement: [],
		conversionFactor: []
	};	
	var pageIndex = 1,
		pageSize = 10,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var init = function() {
		$("#applyMain1").remove();
		$("#financeApplicationList").remove();
		new PCAS("originPlaces", "originPlaces1");			
		oData = {
			pageIndex: pageIndex,
			pageSize: pageSize,
			totalPageCount: totalPageCount,
			totalRecordCount: totalRecordCount
		};
		getCommodityCategory();
		//保证金比例
		$("#apply_main2 select[name=bailRate]").html();
		for(var i = 10; i <= 30; i+=5) {
			var str = '<option value="'+i+'">'+i+'%</option>';
			$("#apply_main2 select[name=bailRate]").append(str);
		}
		tools.loadSelectList("select[name=receive]", "inquireSupplierInfoList.json", "supplierName", "supplierName", null);
		router.init();
		tools.clearNoNumAll($("#main"));
		initEvent();
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			top.location.href = "../login/login.html";
		}
		
		//改变货物类别
		$("#main").on("change", "#commodityCategory2", function() {
			if ($(this).val() != "") {
				inquireBulkstockPageList($(this).val(), $(".commodityNames2"));
				inquireBulkstockCategoryDetail($(this).val());
				$("#commodityCategoryHidden2").val($("#commodityCategory2  option:selected").text());
			} else {
				$(".bulkstockMaterial2").addClass("none");
			}
		});
		
	//改变货物
		$("#main").on("change", ".commodityNames2", function() {
			var commodityName = $(this).parent().find("option:selected").text();
			$(this).parent().find(".bulkstockNames").val(commodityName);
			$(this).parent().find(".measurement").val($(this).parent().find("option:selected").attr("measurement"));
			$(this).parent().find(".conversionFactor").val($(this).parent().find("option:selected").attr("conversionFactor"));
			existBulkstockPledgeRate($(this).val(), null, null);
		});
		
		//更改货物单价
		$("#apply_main2").on("keyup", "input[name=bulkstockPrice]", function(){
			var valuation = $(this).val()*$("#apply_main2 input[name=quantitys]").val();
			if (!isNaN(valuation)) {
				$("#apply_main2 input[name=valuation]").val(valuation);
				
				var valuation1 = (1-$("#apply_main2 select[name=bailRate]").val()/100)*$("#apply_main2 input[name=valuation]").val();
				if (!isNaN(valuation1)) {
					$("#apply_main2 input[name=applicationAmount]").val(valuation1);
				}
			}
		});
		
		//更改保证金比例
		$("#apply_main2").on("change", "select[name=bailRate]", function(){
			var valuation = $("#apply_main2 input[name=bulkstockPrice]").val()*$("#apply_main2 input[name=quantitys]").val();
			if (!isNaN(valuation)) {
				$("#apply_main2 input[name=valuation]").val(valuation);
				
				var valuation1 = (1-$(this).val()/100)*$("#apply_main2 input[name=valuation]").val();
				if (!isNaN(valuation1)) {
					$("#apply_main2 input[name=applicationAmount]").val(valuation1);
				}
			}
		});
		
		$("#apply_main_next2").click(function() {
			if(success == true) {
				base.alert(2,"申请已成功，不能重复提交！");
				return;
			}
			var cm = $(".data[name=creditLineRemains]").html();
			var d = $("#applicationAmount2").val();
			
			if ((d/10000)*1 > cm*1) {
				base.alert(2, "授信额度不足！");
				return;
			}
			
			var promptString = validate.isPhone($("#receiveContactPhone"));
			if (promptString.length > 0) {
				base.alert(2, "收货联系人电话" + promptString);
				return;
			}
			promptString = validate.isPhone($("#deliverContactPhone"));
			if (promptString.length > 0) {
				base.alert(2, "交货联系人电话" + promptString);
				return;
			}
			
			databind.submitDom($(".financeApplicationContent2"), function(data) {
				if(data.datas[0].financeId != undefined && data.datas[0].financeId != "") {
					financeId = data.datas[0].financeId;
					supplementFinanceEvidentiary();
				}
			});

		});
		
		$("#apply_main2 .addSupplier").unbind("click").click(function(){
			var ii = layer.open({
			  title: '新增供应商',
			  type: 1,
			  skin: 'layui-layer-rim', //加上边框
			  area: ['900px', '550px'], //宽高
			  content: html_createSuppliers,
			  btn: ['新增', '取消'],
			  yes: function(){
			  	databind.submitDom($(".createSupplierInfo"), function(){
			  		layer.msg("新增成功！");
			  		layer.close(ii);
			  		$(".select[name=receive]").html("");
			  		tools.loadSelectList("select[name=receive]", "inquireSupplierInfoList.json", "supplierName", "supplierName", null);
			  	});
			  }
			});
			
			new PCAS("registerAddressProvince","registerAddressCity","registerAddressDistrict");
			new PCAS("workAddressProvince","workAddressCity","workAddressDistrict");
			new PCAS("businessLicenceAddress","businessCity","businessDistrict");
		});
		
		//自动补齐
		$("#applyEnterpriseName").on("keyup", function() {
			enterpriseNameAutocomplete();
		});
		
		$("#main").on("change", ".approve input", function() {
			fileElementId = $(this).attr("id");
			uploadMaterial(fileElementId);
		});
		
	};
	
	//获取货物类别
	var getCommodityCategory = function() {
		base.fnAjax({
			action: "inquireBulkstockCategoryPageList.json",
			async: false,
			nocode: true,
			oData: {
				activeState: true,
				productType: productType
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var tpl = $("#commodityCategoryTpl").html();
					var html = juicer(tpl, data);
					$("#commodityCategory2").html(html);
					
					if (productType == 4) {
						
						$("input[name=enterpriseInsuranceNumber]").parents(".dataLine").remove();
						$("input[name=enterpriseForceAmount]").parents(".dataLine").remove();
						$("input[name=enterpriseInsuranceAmount]").parents(".dataLine").remove();
						$("input[name=declaredValue]").parents(".applyDataLine").remove();
						$(".goodsfrom .star").remove();
						$("#receiveProvince").attr("isNull", "0");
						$(".receiveProvince").attr("isNull", "0");
						$("#receiveCity").attr("isNull", "0");
						$(".receiveCity").attr("isNull", "0");
						$(".goodsto .star").remove();
						$("#deliverProvince").attr("isNull", "0");
						$(".deliverProvince").attr("isNull", "0");
						$("#deliverCity").attr("isNull", "0");
						$(".deliverCity").attr("isNull", "0");
						$("#deliverAddress").attr("isNull", "0");
						$("#receiveAddress").attr("isNull", "0");
						$("input[name=bookingSpaceNumber]").parents(".applyDataLine").remove();
//						$("input[name=enterpriseInsuranceNumber]").parents(".applyDataLine").remove();
						$("#addCaseInfo").remove();
						
						$("input[name=weights]").val(1);
						$("input[name=volumes]").val(1).parent().addClass("none");
						$(".valuationLink").attr("style", "visibility: hidden; margin-right: 100px;");
						$(".receiver").html("出质");
						$(".deliver").html("债务");
						
						$(".require_package").remove();
						$(".require_tag").remove();
						$(".require_storage").remove();
						$(".require_keep").remove();
						$(".label_info3").remove();
						$(".line:last").remove();
						
						$(".cargoMark").parent().remove();
						$("#coldStorage").parent().parent().remove();
//						$("#commodityCategory2").attr("disabled", "disabled");
//						$("#commodityCategory2 option[txt='保理业务']").attr("selected", true);
//						$("#commodityCategoryHidden").val("保理业务");
						inquireBulkstockPageList($("#commodityCategory2").val(), $(".commodityNames2"));
						
						tools.loadList("inquireLogisticsCompanyAll.json", $("#deliverList"), $("#deliverList script"), null, function(){
						}, null);
						
						$("#commodityCategoryHidden2").parent().parent().find(".bulkstockCategory").html("产品类别");
						$("#goods1 .label").remove();
						$(".goods_name .bulkstockName").html("产品名称");
						$(".manufacturers").parent().remove();
						$(".bulkstockValuationName").html("发票总价");
						$(".goodsto .select_label").html("出质方地址：");
						$(".goodsto").css("margin-left", "0");
						$(".goodsfrom .select_label").html("债务方地址：");
						$(".goodsfrom").css("margin-left", "0");
						
						$(".labeltitle").html("票据信息");
						$("#progress").attr("src", "../../../res/png/progress_apply11.png");
					} else {
						$(".freightListInfo").remove();
					}
				} else {
					//                  base.alert(2,"信息获取失败");
				}
			}
		});
	};
	
		//大宗商品列表
	var inquireBulkstockPageList = function(bulkstockCategoryId, dom) {
		base.fnAjax({
			action: "inquireBulkstockPageList.json",
			async: false,
			nocode: true,
			oData: {
				bulkstockCategoryId: bulkstockCategoryId,
				pageSize: 100
			}, //传递参数
			fnSuccess: function(data) {
				bulkstockObj = {
					bulkstockId: [],
					bulkstockName: [],
					specificationName: [],
					bulkstockNumber: [],
					measurement: [],
					conversionFactor: []
				};
				if (data.status == 200) {
					for (var j = 0; j < data.datas.length; j++) {
						bulkstockObj.bulkstockName.push(data.datas[j].bulkstockName);
						bulkstockObj.bulkstockId.push(data.datas[j].bulkstockInfoId);
						bulkstockObj.bulkstockNumber.push(data.datas[j].bulkstockNumber);
						bulkstockObj.specificationName.push(data.datas[j].specificationName);
						bulkstockObj.measurement.push(data.datas[j].measurement);
						bulkstockObj.conversionFactor.push(data.datas[j].conversionFactor);
					}
					$(dom).children().remove();
					$(dom).append('<option value="">请选择货物名称</option>');
					for (var j = 0; j < bulkstockObj.bulkstockName.length; j++) {
						var str = '<option value="' + bulkstockObj.bulkstockId[j] + '" measurement="' + bulkstockObj.measurement[j] + '"  conversionFactor="' + bulkstockObj.conversionFactor[j] + '">' + bulkstockObj.bulkstockName[j] + '(' + bulkstockObj.specificationName[j] + ')' + '</option>';
						$(dom).append(str);
					}
				} else {
					//                  base.alert(2,"信息获取失败");
				}
			}
		});
	};
	
	//获取货物类别详情
	var inquireBulkstockCategoryDetail = function(bulkstockCategoryId) {
		base.fnAjax({
			action: "inquireBulkstockCategoryDetail.json",
			async: true,
			nocode: true,
			oData: {
				bulkstockCategoryId: bulkstockCategoryId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var str = "";
					for (var j = 0; j < data.datas[0].templates.length; j++) {
						str += data.datas[0].templates[j].templateName + ",";
					}
					str = str.substring(0, str.length - 1);
					$("#bulkstockMaterial2").html(str);
					$(".bulkstockMaterial2").removeClass("none");
					$(".bulkstockMaterial2").css("display", "block");
					
					var tpl = $("#approveTpl").html(); //证明资料
					var html = juicer(tpl, data);
					$("#approveBody").html(html);
				} else {
					//                  base.alert(2,"信息获取失败");
				}
			}
		});
	};
	
	//判断货物融资权限
	var existBulkstockPledgeRate = function(bulkstockInfoId, pledgeRate, loanRate) {
		base.fnAjax({
			action: "existBulkstockPledgeRate.json",
			async: false,
			nocode: true,
			oData: {
				bulkstockInfoId: bulkstockInfoId,
				productType: productType,
				pledgeRate: pledgeRate,
				loanRate: loanRate,
				enterpriseId: function() {
					return $("#enterpriseId").val();
				}
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					if (!data.datas[0].isExist) {
						layer.msg("对不起，您暂无该货物的融资权限，请联系客服!");
					}
				} else {
					layer.msg(data.message);
				}
			}
		});
	};
	
	var inquireCurrentEnterpriseDetail = function() {
		base.fnAjax({
			action: "inquireEnterpriseDetail.json",
			async: false,
			oData: {
				enterpriseId: enterpriseId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					databind.fillForm($(".creditLineDom"), data.datas[0].enterpriseGradeDetail);
					$(".data[name=creditLine]").html(($(".data[name=creditLine]").html()/10000).toFixed(2));
					$(".data[name=creditAlready]").html(($(".data[name=creditAlready]").html()/10000).toFixed(2));
					$(".data[name=creditLineRemains]").html(($(".data[name=creditLineRemains]").html()/10000).toFixed(2));
				} else {
					//                  base.alert(2,"信息获取失败");
				}
			}
		});
	};
	
	//公司名称自动补齐
	var enterpriseNameAutocomplete = function() {
		
		//自动补全
		$("#applyEnterpriseName").autocomplete(seajs.data.handler + "inquireEnterprisePageList.json", {
			minChars: 1,
			max: 10,
			width: 305,
			matchCase: false, //不区分大小写
			scroll: false,
			dataType: 'json',
			scrollHeight: 500,
			//此处为传递而外的参数
			extraParams: {
				pageSize: 50,
				sessionUuid: base.getData("sid"),
				appKey: base.getData("appKey"),
				enterpriseName: function() {
					return $("#applyEnterpriseName").val();
				},
				isPassed: true
			},
			//需要把data转换成json数据格式                      
			parse: function(data) {
				return $.map(eval(data.datas), function(row) {
					return {
						data: row,
						value: row.enterpriseName, //此处无需把全部列列出来，只是两个关键列
						result: row.enterpriseName
					}
				});
			},
			formatItem: function(data, i, total) {
				if ($("#applyEnterpriseName").hasClass('nonemorelist')) {
					$("#applyEnterpriseName").removeClass('nonemorelist');
					return;
				};
				return "<table><tr enterpriseId=" + data.enterpriseId + "><td>" + data.enterpriseName + "</td></tr></table>";
			},
			formatMatch: function(data, i, total) {
				return data.enterpriseName;
			},
			formatResult: function(data, value) {
				return data.enterpriseName;
			}
		}).result(function(event, data, formatted) { //回调
			$("#enterpriseId").val(data.enterpriseId);
			enterpriseId = data.enterpriseId;
			if ($("#applyEnterpriseName").hasClass('nonemorelist')) {
				$("#applyEnterpriseName").removeClass('nonemorelist');
			} else {
				$("#applyEnterpriseName").addClass('nonemorelist');
			};
			inquireCurrentEnterpriseDetail();
		});
	}
	
	//增补融资申请证明材料
	var supplementFinanceEvidentiary = function() {
		var uploadMust = $(".uploadMust");
			if (uploadMust.length == 0) {
				flag = true;
			}
			for (var j = 0; j < uploadMust.length; j++) {
				if ($(uploadMust[j]).parent().parent().find("a").length <= 0) {
					$(".error_info").css("visibility", "visible");
					flag = false;
					break;
				} else {
					flag = true;
				}
			}
			if (flag) {
					if ($(".financeEvidentiary").length > 0) {
					$.each($(".financeEvidentiary"), function(i, val) {
						materialFileuuid.push($(this).attr("materialFileuuid"));
						templateName.push($(this).attr("templateName"));
						templateId.push($(this).attr("templateId"));
						evidentiaryCategoryId.push($(this).attr("evidentiaryCategoryId"));
						evidentiaryId.push($(this).attr("evidentiaryId"));
		
					});
		
					base.fnAjax({
						action: "supplementFinanceEvidentiary.json",
						async: false,
						nocode: true,
						oData: {
							materialFileuuid: materialFileuuid,
							evidentiaryId: evidentiaryId,
							templateName: templateName,
							templateId: templateId,
							evidentiaryCategoryId: evidentiaryCategoryId,
							financeId: financeId
						}, //传递参数
						fnSuccess: function(data) {
							tools.cancelProtectDoubleClick();
							if (data.status == 200) {
								success = true;
								base.alert(1,"申请成功");
							} else {
								base.alert(2, data.message);
							}
						}
					});
				}else{
					success = true;
					base.alert(1,"申请成功");
				}
			} else {
				$(".error_info").css("visibility", "visible");
			}
	};

			//上传文件
	var uploadMaterial = function(fileElementId) {
		$.ajaxFileUpload({
			url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
			secureuri: false,
			fileElementId: fileElementId,
			dataType: 'json',
			async: true,
			success: function(data) {
				var dom = $(document.getElementById(fileElementId));
				dom.before(str1);
				dom.parent().find("a:last").attr({
					"href": "/finance/api/v1.0/downloadFile.file?fileUuid=" + data.data[0].fileUuid,
					"materialFileuuid": data.data[0].fileUuid,
					"templateName": dom.parents(".materiaData").attr("templateName"),
					"templateId": dom.parents(".materiaData").attr("templateId"),
					"evidentiaryCategoryId": 0,
					"evidentiaryId": 0
				});
				dom.parent().find("span:last").html(data.data[0].fileName);
				dom.parent().find(".sub1:last").click(function() {
					$(this).parent().remove();
				});
			},
			complete: function(xml) {},
			error: function(data, status, e) {
				if (data.msg == null) {
					base.alert(2, "文件太大无法上传");
				} else {
					base.alert(2, data.msg);
				}
			}
		});
	};
		
	return {
		init: init
	};
});

